import * as fs from 'fs';
import * as path from 'path';

export interface PatternRefactorResult {
  success: boolean;
  message: string;
  generatedFiles: string[];
  modifiedFiles: string[];
  patternType: string;
  refactorDetails?: string[];
  errors?: string[];
}

/**
 * 设计模式重构器 - 将if/else重构为Strategy模式等
 */
export class DesignPatternRefactor {

  async refactorToStrategy(
    filePath: string,
    methodName: string,
    strategyInterfaceName: string,
    projectPath: string
  ): Promise<PatternRefactorResult> {
    const result: PatternRefactorResult = {
      success: false,
      message: '',
      generatedFiles: [],
      modifiedFiles: [],
      patternType: 'Strategy',
      refactorDetails: [],
      errors: []
    };

    try {
      console.error(`[DesignPatternRefactor] 开始Strategy模式重构`);
      
      const content = fs.readFileSync(filePath, 'utf-8');
      const packageName = this.extractPackageName(content);
      
      // 分析条件语句
      const conditionalBlocks = this.extractConditionalBlocks(content, methodName);
      
      if (conditionalBlocks.length === 0) {
        result.message = '未找到可重构的条件语句';
        result.success = true;
        return result;
      }

      // 生成策略接口
      const strategyInterface = this.generateStrategyInterface(strategyInterfaceName, packageName);
      const interfaceFile = path.join(path.dirname(filePath), `${strategyInterfaceName}.java`);
      fs.writeFileSync(interfaceFile, strategyInterface, 'utf-8');
      result.generatedFiles.push(interfaceFile);

      // 生成具体策略类
      for (let i = 0; i < conditionalBlocks.length; i++) {
        const block = conditionalBlocks[i];
        const strategyClassName = `${strategyInterfaceName}Impl${i + 1}`;
        const strategyClass = this.generateConcreteStrategy(strategyClassName, strategyInterfaceName, block.code, packageName);
        const strategyFile = path.join(path.dirname(filePath), `${strategyClassName}.java`);
        fs.writeFileSync(strategyFile, strategyClass, 'utf-8');
        result.generatedFiles.push(strategyFile);
      }

      // 生成策略工厂
      const factoryClassName = `${strategyInterfaceName}Factory`;
      const factoryClass = this.generateStrategyFactory(factoryClassName, strategyInterfaceName, conditionalBlocks, packageName);
      const factoryFile = path.join(path.dirname(filePath), `${factoryClassName}.java`);
      fs.writeFileSync(factoryFile, factoryClass, 'utf-8');
      result.generatedFiles.push(factoryFile);

      result.success = true;
      result.message = `成功重构为Strategy模式，生成 ${result.generatedFiles.length} 个文件`;

    } catch (error) {
      result.errors?.push(`Strategy模式重构失败: ${error}`);
      result.message = `Strategy模式重构失败: ${error}`;
    }

    return result;
  }

  private extractConditionalBlocks(content: string, methodName: string): Array<{condition: string, code: string}> {
    // 简化实现：查找if/else语句块
    const blocks: Array<{condition: string, code: string}> = [];
    
    // 这里应该有更复杂的AST解析，暂时简化
    const ifPattern = /if\s*\(([^)]+)\)\s*\{([^}]+)\}/g;
    let match;
    
    while ((match = ifPattern.exec(content)) !== null) {
      blocks.push({
        condition: match[1].trim(),
        code: match[2].trim()
      });
    }
    
    return blocks;
  }

  private generateStrategyInterface(interfaceName: string, packageName: string): string {
    let content = '';
    
    if (packageName) {
      content += `package ${packageName};\n\n`;
    }
    
    content += `/**\n`;
    content += ` * 策略接口 - 自动生成\n`;
    content += ` */\n`;
    content += `public interface ${interfaceName} {\n`;
    content += `    void execute();\n`;
    content += `}\n`;
    
    return content;
  }

  private generateConcreteStrategy(className: string, interfaceName: string, code: string, packageName: string): string {
    let content = '';
    
    if (packageName) {
      content += `package ${packageName};\n\n`;
    }
    
    content += `/**\n`;
    content += ` * 具体策略实现 - 自动生成\n`;
    content += ` */\n`;
    content += `public class ${className} implements ${interfaceName} {\n\n`;
    content += `    @Override\n`;
    content += `    public void execute() {\n`;
    content += `        ${code}\n`;
    content += `    }\n`;
    content += `}\n`;
    
    return content;
  }

  private generateStrategyFactory(factoryName: string, interfaceName: string, blocks: Array<{condition: string, code: string}>, packageName: string): string {
    let content = '';
    
    if (packageName) {
      content += `package ${packageName};\n\n`;
    }
    
    content += `/**\n`;
    content += ` * 策略工厂 - 自动生成\n`;
    content += ` */\n`;
    content += `public class ${factoryName} {\n\n`;
    content += `    public static ${interfaceName} getStrategy(String type) {\n`;
    
    for (let i = 0; i < blocks.length; i++) {
      const condition = `"type${i + 1}"`;
      content += `        if (${condition}.equals(type)) {\n`;
      content += `            return new ${interfaceName}Impl${i + 1}();\n`;
      content += `        }\n`;
    }
    
    content += `        throw new IllegalArgumentException("Unknown strategy type: " + type);\n`;
    content += `    }\n`;
    content += `}\n`;
    
    return content;
  }

  private extractPackageName(content: string): string {
    const match = content.match(/package\s+([^;]+);/);
    return match ? match[1].trim() : '';
  }
}